package apps.softtech.fastmarket;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import apps.softtech.Utility.ApplicationConstants;
import apps.softtech.Utility.ConnectionDetector;
import apps.softtech.Utility.RequestDataFromServer;
import apps.softtech.fastmarket.adapter.AdapterProductList;
import apps.softtech.fastmarket.model.Category;
import apps.softtech.fastmarket.model.DatabaseHandler;
import apps.softtech.fastmarket.model.Product;

@SuppressLint("NewApi")
public class FragmentTabCategory extends Fragment {

	ListView lvProductsList;
	AdapterProductList mAdapterProductList;
	ArrayList<Product> mProductsList = new ArrayList<Product>();
	ArrayList<Product> mProductsListTest = new ArrayList<Product>();
	DatabaseHandler dbh;
	int categoryId;
	DisplayImageOptions options;
	ConnectionDetector cd;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
    }
  
    boolean isClick=false;
    TextView tv ;
    
    private void testInsertProductList() {

//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[1],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[2],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[3],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[4],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[5],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[6],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[7],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[8],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[9],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[10],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[11],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[12],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[13],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[14],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[15],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[16],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[17],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[18],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[19],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[20],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[21],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[22],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[23],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[24],""));
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[25],""));
//    	
//    	
//    	
//    	mProductsListTest.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[23],""));
//    	mProductsListTest.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[24],""));
//    	mProductsListTest.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2,Constants.IMAGES[25],""));
//    	
//    	
//    	
//    	mProductsList.addAll(0, mProductsListTest);
//    	
//    	mAdapterProductList = new AdapterProductList(mProductsList, getActivity(),options);
//
//    	for(int i=0;i<200;i++){
//    	mProductsList.add(new Product(1, 1, "10/10/2014", 1, "9/10/2014", 2, "https://lh5.googleusercontent.com/-MlzebY0K_gw/" +
//    			"UfGJB6ejIwI/AAAAAAAAYBA/wjWDk40CH88/s553-no/13%2B-%2B1",""));
//    	}
//    	mAdapterProductList = new AdapterProductList(mProductsList, getActivity());

//    	lvProductsList.setAdapter(mAdapterProductList);
    	
	}



	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				getActivity()).build();
		ImageLoader.getInstance().init(config);
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.button_border)
				.showImageForEmptyUri(R.drawable.ic_launcher)
				.showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
				.cacheOnDisk(true).considerExifParams(true)
				.displayer(new RoundedBitmapDisplayer(2)).build();

		cd = new ConnectionDetector(getActivity());
		dbh = new DatabaseHandler(getActivity());
		//
		// receiver id
		//
		getActivity().registerReceiver(
				mBroadcastReceiverParent,
				new IntentFilter(
						ApplicationConstants.RECEIVER_CATEGORY_ID_PARENT));
		getActivity().registerReceiver(
				mBroadcastReceiverChild,
				new IntentFilter(
						ApplicationConstants.RECEIVER_CATEGORY_ID_CHILD));

		View v = inflater.inflate(R.layout.fragment_category, container, false);
		lvProductsList = (ListView) v.findViewById(R.id.lvProductsList);
		// testInsertProductList();
		return v;
	}

	@Override
	public void onDestroy() {
		dbh.close();
		super.onDestroy();
	}

	/**
	 * settup product list
	 */
	private void setProductsList() {
		mAdapterProductList = new AdapterProductList(mProductsList,
				getActivity(), options);
		lvProductsList.setAdapter(mAdapterProductList);
	}

	/**
	 * 
	 * get product list parent
	 * 
	 */
	class AsyncTaskGetProductsListParent extends AsyncTask<Void, Void, Void> {
		ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(getActivity());
			pd.setMessage("Loading....");
			pd.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				for (int k = 0; k < mCategoriesListChild.size(); k++) {
					idCategory = mCategoriesListChild.get(k).getCategoryId();
					JSONArray jsonData = new JSONArray();
					JSONObject jsonCategoryParentList = new JSONObject(
							new RequestDataFromServer()
									.requestProductsList(idCategory));
					int success = jsonCategoryParentList.getInt("success");
					if (success == 1) {
						jsonData = jsonCategoryParentList.getJSONArray("data");
						Log.v("" + idCategory + ":", jsonData.toString());
						for (int i = 0; i < jsonData.length(); i++) {
							JSONObject jsonList = new JSONObject(jsonData
									.getJSONObject(i).toString());
							dbh.insertProduct(new Product(jsonList
									.getInt("st_ProductId"), jsonList
									.getInt("st_UserId"), jsonList
									.getString("st_CreatedDate"), jsonList
									.getInt("st_CategoryId"), jsonList
									.getString("st_LastUpdate"), jsonList
									.getInt("st_IsComplete"), jsonList
									.getString("st_Description"), ""));
						}
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			for (int k = 0; k < mCategoriesListChild.size(); k++) {
				idCategory = mCategoriesListChild.get(k).getCategoryId();
				mProductsList = (ArrayList<Product>) dbh.getProduct(null,
						Product.CATEGORY_ID + " =?", new String[] { ""
								+ idCategory }, null, null);

			}
			setProductsList();
			try {
				pd.dismiss();
			} catch (Exception e) {
			}
			super.onPostExecute(result);
		}

	}

	/**
	 * get product list
	 * 
	 */
	class AsyncTaskGetProductsList extends AsyncTask<Void, Void, Void> {
		ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(getActivity());
			pd.setMessage("Loading....");
			pd.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				JSONArray jsonData = new JSONArray();
				JSONObject jsonCategoryParentList = new JSONObject(
						new RequestDataFromServer()
								.requestProductsList(idCategoryChild));
				int success = jsonCategoryParentList.getInt("success");
				if (success == 1) {
					jsonData = jsonCategoryParentList.getJSONArray("data");
					Log.v("" + idCategory + ":", jsonData.toString());
					for (int i = 0; i < jsonData.length(); i++) {
						JSONObject jsonList = new JSONObject(jsonData
								.getJSONObject(i).toString());
						dbh.insertProduct(new Product(jsonList
								.getInt("st_ProductId"), jsonList
								.getInt("st_UserId"), jsonList
								.getString("st_CreatedDate"), jsonList
								.getInt("st_CategoryId"), jsonList
								.getString("st_LastUpdate"), jsonList
								.getInt("st_IsComplete"), jsonList
								.getString("st_Description"), ""));
					}
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			mProductsList = (ArrayList<Product>) dbh.getProduct(null,
					Product.CATEGORY_ID + " =?", new String[] { ""
							+ idCategoryChild }, null, null);

			setProductsList();
			try {
				pd.dismiss();
			} catch (Exception e) {
			}
			super.onPostExecute(result);
		}

	}

	/**
	 * id category
	 */
	int idCategory;
	/**
	 * id category parent to get child
	 */
	int idCategoryParent = -1;
	/**
	 * id category child to get all
	 */
	int idCategoryChild = -1;
	/**
	 * receive id category parent
	 */
	BroadcastReceiver mBroadcastReceiverParent = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle extra = intent.getExtras();
			if (extra != null) {
				idCategoryParent = extra.getInt("st_CategoryId");
				Log.v("Frabment Tab", "" + idCategoryParent);
				getAllCategoryChild();
				// getProductListParent();
			}
		}

	};
	/**
	 * receive id category child
	 */
	BroadcastReceiver mBroadcastReceiverChild = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle extra = intent.getExtras();
			if (extra != null) {
				idCategoryChild = extra.getInt("st_CategoryId");

				if (idCategoryChild != -1) {
					mProductsList.clear();
					setProductsList();
					if (cd.isConnectingToInternet()) {
						dbh.deleteProduct(Product.PRODUCT_ID + " =>0", null);
						new AsyncTaskGetProduct().execute(idCategoryChild);
					} else {
						mCategoriesListChild = (ArrayList<Category>) dbh
								.getCategory(null, Category.PARENT_CATEGORY_ID
										+ " =?", new String[] { ""
										+ idCategoryParent }, null, null);
						if (mCategoriesListChild.size() != 0) {
							for (int i = 0; i < mCategoriesListChild.size(); i++) {
								int idCategory = mCategoriesListChild.get(i)
										.getCategoryId();
								ArrayList<Product> ProductsList = (ArrayList<Product>) dbh
										.getProduct(null, Product.CATEGORY_ID
												+ " =?", new String[] { ""
												+ idCategory }, null, null);
								mProductsList.addAll(ProductsList);
							}
							if (mProductsList.size() != 0) {
								setProductsList();
							}
						}
					}
				}
			}
		}

	};
	/**
	 * list category child
	 */
	ArrayList<Category> mCategoriesListChild = new ArrayList<Category>();

	/**
	 * get category child
	 * 
	 * @param id
	 */
	private void getAllCategoryChild() {
		if (idCategoryParent != -1) {
			mProductsList.clear();
			setProductsList();
			if (cd.isConnectingToInternet()) {
				new AsyncTackGetCategoryChild().execute();
			} else {
				mCategoriesListChild = (ArrayList<Category>) dbh.getCategory(
						null, Category.PARENT_CATEGORY_ID + " =?",
						new String[] { "" + idCategoryParent }, null, null);
				if (mCategoriesListChild.size() != 0) {
					for (int i = 0; i < mCategoriesListChild.size(); i++) {
						int idCategory = mCategoriesListChild.get(i)
								.getCategoryId();
						ArrayList<Product> ProductsList = (ArrayList<Product>) dbh
								.getProduct(null, Product.CATEGORY_ID + " =?",
										new String[] { "" + idCategory }, null,
										null);
						mProductsList.addAll(ProductsList);
					}
					if (mProductsList.size() != 0) {
						setProductsList();
					}
				}

			}
		}
	}

	/**
	 * asystack get category child
	 */
	class AsyncTackGetCategoryChild extends AsyncTask<String, String, String> {
		ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(getActivity());
			pd.setMessage("Loading....");
			pd.show();
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			try {
				JSONArray jsonData = new JSONArray();
				JSONObject jsonCategoryParentList = new JSONObject(
						new RequestDataFromServer()
								.requestCategoryChildList(idCategoryParent));
				int success = jsonCategoryParentList.getInt("success");
				if (success == 1) {
					jsonData = jsonCategoryParentList.getJSONArray("data");
					for (int i = 0; i < jsonData.length(); i++) {
						JSONObject jsonList = new JSONObject(jsonData
								.getJSONObject(i).toString());
						mCategoriesListChild.add(new Category(jsonList
								.getInt("st_CategoryId"), jsonList
								.getString("st_CategoryName"), jsonList
								.getString("st_Description"), jsonList
								.getInt("st_ParentCategoryId"), jsonList
								.getInt("st_CategoryLevel")));
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			if (mCategoriesListChild.size() != 0) {
				dbh.deleteProduct(Product.PRODUCT_ID + " >=0", null);
				for (int i = 0; i < mCategoriesListChild.size(); i++) {
					int idCategory = mCategoriesListChild.get(i)
							.getCategoryId();
					new AsyncTaskGetProduct().execute(idCategory);
				}
			}
			pd.dismiss();
			super.onPostExecute(result);
		}

	}

	/**
	 * get product
	 */
	class AsyncTaskGetProduct extends AsyncTask<Integer, Void, Void> {

		@Override
		protected Void doInBackground(Integer... params) {
			try {
				JSONArray jsonData = new JSONArray();
				JSONObject jsonCategoryParentList = new JSONObject(
						new RequestDataFromServer()
								.requestProductsList(params[0]));
				int success = jsonCategoryParentList.getInt("success");
				if (success == 1) {
					jsonData = jsonCategoryParentList.getJSONArray("data");
					for (int i = 0; i < jsonData.length(); i++) {
						JSONObject jsonList = new JSONObject(jsonData
								.getJSONObject(i).toString());
						Product product = new Product();
						product.setAvatarPath(jsonList
								.getString("st_AvatarPath"));
						product.setProductName(jsonList
								.getString("st_ProductName"));
						product.setCreatedDate(jsonList
								.getString("st_CreatedDate"));
						product.setPrice(jsonList.getInt("st_Price"));
						dbh.insertProduct(product);
						mProductsList.add(product);
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (mProductsList.size() != 0) {
				Log.v("fragment category: ", "" + mCategoriesListChild.size());
				setProductsList();
			}
			super.onPostExecute(result);
		}

	}
}